# Authentication backend that queries ae.utbm.fr accounts.

import SOAPpy as soap
from django.conf import settings
from django.contrib.auth.models import User

class AeAuthBackend(object):
    """Authenticate against the AE website SSO interface."""

    SUPERFLUX_AID = 77
    SUPERFLUX_MINION_MIN_LEVEL = 2

    def __init__(self):
        self.server = soap.SOAPProxy("https://ae.utbm.fr/apisso.php")

    def _get_uid_from_ae2(self, username, password):
        try:
            uid = int(self.server.testLogin(apikey=settings.AE2_API_KEY,
                                            login=username, password=password))
        except (IOError, ValueError, soap.Error):
            return None

        return uid or None

    def _is_superflux_minion(self, uid):
        try:
            result = int(self.server.testAssoRole(
                    apikey=settings.AE2_API_KEY,
                    uid=uid, aid=self.SUPERFLUX_AID,
                    role=self.SUPERFLUX_MINION_MIN_LEVEL))
        except (IOError, ValueError, soap.Error):
            return False
        else:
            return (result == 1)

    def authenticate(self, username=None, password=None):
        if not (username and password):
            return None

        uid = self._get_uid_from_ae2(username, password)
        if not (uid and self._is_superflux_minion(uid)):
            return None

        # User authenticated and a Superflux member.
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            # Create a new user object for this AE user.
            user = User(username=username, password='AE2 auth')
            user.save()
        return user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
